<?php

namespace App\Store\Controllers\Financial\Goods;

use App\Common\Services\Common;
use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsStyle;
use App\Store\Models\Goods\GoodsAllotInfolist;
use App\Store\Models\Goods\GoodsReplenishInfolist;
use App\Store\Models\Goods\GoodsReturnInfolist;
use App\Store\Models\Goods\GoodsStockinInfolist;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\SiteStore;
use Maatwebsite\Excel\Facades\Excel;

class GoodsStockinSummaryController extends Controller
{

    /**
     * 入库汇总
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getlist(Request $request)
    {
        $data = $this->getdata($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }

    /**
     *
     * 入库汇总导出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function doexport(Request $request)
    {
        $data = $this->getdata($request);
        if (!$data) {
            return response()->json(['code' => '001', 'msg' => '导出失败']);
        }

        $store_id = $request['store_id'];
        $store_name = SiteStore::query()->where('id', $store_id)->value('store_name');

        $row = [

            ['goods_category_id' => '入库汇总表'],
            ['goods_category_id' => '所属门店：' . $store_name],
            [
                'goods_category_id' => '商品类别',
                'total_count' => '总件数',
                'total_piece_weight' => '总件重',
                'total_netglod_weight' => '总金重',
                'total_label_price' => '商品标价',
                'total_cost_fee' => '总成本',
                'goods_style_id' => '款式',
                'count' => '件数',
                'piece_weight' => '总件重',
                'netglod_weight' => '总金重',
                'label_price' => '商品标价',
                'cost_fee' => '成本',
            ]];

        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[2]['total_cost_fee']);
            unset($row[2]['cost_fee']);
        }
        $initcont = count($row) + 1;
        $mergecell = [];
        foreach ($data as $val) {
            $mergecell[] = 'A' . $initcont . ':A' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'B' . $initcont . ':B' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'C' . $initcont . ':C' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'D' . $initcont . ':D' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'E' . $initcont . ':E' . $initcont + count($val['style_list']) - 1;
            $mergecell[] = 'F' . $initcont . ':F' . $initcont + count($val['style_list']) - 1;
            $initcont = $initcont + count($val['style_list']);
            foreach ($val['style_list'] as $k1 => $v) {
                if ($k1 == 0) {
                    $exceldata[] = [
                        'goods_category_id' => $val['category_name'],
                        'total_count' => $val['count'],
                        'total_piece_weight' => $val['total_piece_weight'],
                        'total_netglod_weight' => $val['total_netglod_weight'],
                        'total_label_price' => $val['label_price'],
                        'total_cost_fee' => $val['total_cost_fee'],
                        'goods_style_id' => $v['style_name'],
                        'count' => $v['count'],
                        'piece_weight' => $v['total_piece_weight'],
                        'netglod_weight' => $v['total_netglod_weight'],
                        'label_price' => $v['label_price'],
                        'cost_fee' => $v['total_cost_fee'],
                    ];
                } else {
                    $exceldata[] = [
                        'goods_category_id' => $val['category_name'],
                        'total_count' => $val['count'],
                        'total_piece_weight' => $val['total_piece_weight'],
                        'total_netglod_weight' => $val['total_netglod_weight'],
                        'total_label_price' => $val['label_price'],
                        'total_cost_fee' => $val['total_cost_fee'],
                        'goods_style_id' => $v['style_name'],
                        'count' => $v['count'],
                        'piece_weight' => $v['total_piece_weight'],
                        'netglod_weight' => $v['total_netglod_weight'],
                        'label_price' => $v['label_price'],
                        'cost_fee' => $v['total_cost_fee'],
                    ];
                }
            }
        }
        $filename = '入库汇总表导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, [], $mergecell), $filename);
    }


    /**
     *
     * 数据处理
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function getdata(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $cateList = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get(['category_name', 'id'])
            ->pluck('category_name', 'id')
            ->toArray();

        $styleList = GoodsStyle::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1])
            ->get(['style_name', 'id'])
            ->pluck('style_name', 'id')
            ->toArray();

        $where = [];
        $type = (int)$request['type'] ?? 0;
        $store_id = $request['store_id'] ?? 0;
        $where[] = ['cp_id', '=', $cp_id];
        $audit_status = $request['audit_status'] ?? 1;
        if ($audit_status > 1) {
            $where[] = ['audit_status', '=', $audit_status];
        } else {
            $where[] = ['audit_status', '<>', 1];
        }

        if (!empty($store_id)) {
            $where[] = ['store_id', '=', $store_id];
        }

        if (!empty($request['goods_style_id'])) {
            $where[] = ['goods_style_id', '=', $request['goods_style_id']];
        }

        if (!empty($request['goods_category_id'])) {
            $where[] = ['goods_category_id', '=', $request['goods_category_id']];
        }
        if (!empty($request['supply_id'])) {
            $where[] = ['supply_id', '=', $request['supply_id']];
        }
        if (!empty($request['goods_brand_id'])) {
            $where[] = ['goods_brand_id', '=', $request['goods_brand_id']];
        }


        // 权限
        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        $store_ids = is_array($store_ids) ? $store_ids : ($store_ids > 0 ? [$store_ids] : []);

        $virtuallyCate = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1, 'is_virtually' => 1])
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                if (is_array($store_ids)) {
                    $query->whereIn('store_id', $store_ids);
                } else {
                    $query->where('store_id', $store_ids);
                }
            })
            ->get(['id'])
            ->pluck('id')
            ->toArray();


        $cateIds = [];
        // 查询柜组
        if (!empty($request['goods_cabinetgroup_id'])) {
            $cateIds = GoodsCategory::query()
                ->where(['goods_cabinetgroup_id' => $request['goods_cabinetgroup_id'], 'is_del' => 1, 'cp_id' => $cp_id])
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->pluck('id')
                ->toArray();
        }
        // 时间段查询
        $start_time = $request['start_time'];
        $end_time = $request['end_time'];

        if (!empty($start_time) && !empty($end_time)) {

            $start_time = (!is_numeric($start_time) && strtotime($start_time) > 0) ? strtotime($start_time) : intval($start_time);
            $end_time = (!is_numeric($end_time) && strtotime($end_time) > 0) ? strtotime($end_time) : intval($end_time);
            $start_time = strtotime(date('Y-m-d', $start_time) . ' 00:00:00');
            $end_time = strtotime(date('Y-m-d', $end_time) . ' 23:59:59');

            $where[] = ['audit_at', '>=', $start_time];
            $where[] = ['audit_at', '<=', $end_time];
        }


        // 1入库，2补货，调拨(3调出、4调入)，5返厂
        if ($type == 1) {
            $list = GoodsStockinInfolist::query()
                ->where($where)
                ->where('count', '>', 0)
                ->when(count($virtuallyCate) > 0, function ($query) use ($virtuallyCate) {
                    $query->whereNotIn('goods_category_id', $virtuallyCate);
                })
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($cateIds) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->get(['goods_style_id', 'count', 'total_piece_weight', 'total_netglod_weight', 'label_price', 'total_cost_fee', 'goods_category_id', 'goods_sn_code'])
                ->toArray();

        } elseif ($type == 2) {
            // 补货
            $list = GoodsReplenishInfolist::query()
                ->where($where)
                ->where('count_new', '>', 0)
                ->when(count($virtuallyCate) > 0, function ($query) use ($virtuallyCate) {
                    $query->whereNotIn('goods_category_id', $virtuallyCate);
                })
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->selectRaw('goods_style_id, count_new as count, total_piece_weight_new as total_piece_weight,total_netglod_weight_new as total_netglod_weight, label_price, total_cost_fee, goods_category_id, goods_sn_code')
                ->get()
                ->toArray();
        } elseif (in_array($type, [3, 4])) {

            foreach ($where as $key => $val) {
                if ($val[0] == 'store_id') {
                    unset($where[$key]);
                }
                if ($val[0] == 'goods_category_id') {
                    unset($where[$key]);
                }
            }

            //调拨(3调出、4调入)
            if ($type == 3) {
                if ($store_id > 0) {
                    $where[] = ['start_store_id', '=', $store_id];
                }
                if (!empty($request['goods_category_id'])) {
                    $where[] = ['goods_category_id', '=', $request['goods_category_id']];
                }

                $field = 'goods_style_id,count_new as count,total_piece_weight,total_netglod_weight,label_price,total_cost_fee,goods_category_id,goods_sn_code';
            } else {
                if ($store_id > 0) {
                    $where[] = ['target_store_id', '=', $store_id];
                }
                if (!empty($request['goods_category_id'])) {
                    $where[] = ['target_category_id', '=', $request['goods_category_id']];
                }
                $field = 'goods_style_id,count_new as count,total_piece_weight,total_netglod_weight,label_price,total_cost_fee,target_category_id as goods_category_id,goods_sn_code';
            }


            $where = array_values($where);


           // print_r($where);exit;

            $list = GoodsAllotInfolist::query()
                ->where($where)
                ->where('count_new', '>', 0)
                ->when($type == 3, function ($query) use ($store_ids, $cateIds, $virtuallyCate) {
                    if (count($store_ids) > 0) {
                        $query->whereIn('start_store_id', $store_ids);
                    }
                    if (count($cateIds) > 0) {
                        $query->whereIn('goods_category_id', $cateIds);
                    }
                    if (count($virtuallyCate) > 0) {
                        $query->whereNotIn('goods_category_id', $virtuallyCate);
                    }
                })
                ->when($type == 4, function ($query) use ($store_ids, $cateIds, $virtuallyCate) {
                    if (count($store_ids) > 0) {
                        $query->whereIn('target_store_id', $store_ids);
                    }
                    if (count($cateIds) > 0) {
                        $query->whereIn('target_category_id', $cateIds);
                    }
                    if (count($virtuallyCate) > 0) {
                        $query->whereNotIn('target_category_id', $virtuallyCate);
                    }
                })
                ->selectRaw($field)
                ->get()
                ->toArray();

        } elseif ($type == 5) {
            $list = GoodsReturnInfolist::query()
                ->where($where)
                ->where('count_new', '>', 0)
                ->when(count($virtuallyCate) > 0, function ($query) use ($virtuallyCate) {
                    $query->whereNotIn('goods_category_id', $virtuallyCate);
                })
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereNotIn('goods_category_id', $cateIds);
                })
                ->when(count($store_ids) > 0 && (int)$type == 3, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->get(['goods_style_id', 'count_new as count', 'total_piece_weight', 'total_netglod_weight', 'label_price', 'total_cost_fee', 'goods_category_id', 'goods_sn_code'])
                ->toArray();
        } else {
            return response()->json(['code' => '001', 'msg' => '传入的类型错误']);
        }

        $groupData = [];
        foreach ($list as &$val) {
            $val['category_name'] = $cateList[$val['goods_category_id']] ?? '';
            $val['style_name'] = $styleList[$val['goods_style_id']] ?? '';
            $val['total_piece_weight'] = $val['total_piece_weight'] * 1000;
            $val['total_netglod_weight'] = $val['total_netglod_weight'] * 1000;
            $val['label_price'] = $val['label_price']*$val['count'];
            $groupData[$val['goods_category_id']][] = $val;
        }


        $newData = [];
        foreach ($groupData as $goods_category_id => $group) {
            $data = [];
            $data['goods_category_id'] = $goods_category_id;
            $data['category_name'] = $cateList[$goods_category_id] ?? '';
            $data['count'] = array_sum(array_column($group, 'count'));
            $data['total_piece_weight'] = bcdiv(array_sum(array_column($group, 'total_piece_weight')), 1000, 3);
            $data['total_netglod_weight'] = bcdiv(array_sum(array_column($group, 'total_netglod_weight')), 1000, 3);
            $data['label_price'] = bcdiv(array_sum(array_column($group, 'label_price')), 100, 2);
            $data['total_cost_fee'] = bcdiv(array_sum(array_column($group, 'total_cost_fee')), 100, 2);

            // 分组
            $styleArr = [];
            foreach ($group as $g) {
                $styleArr[$g['goods_style_id']][] = $g;
            }

            $styleData = [];
            foreach ($styleArr as $goods_style_id => $item) {
                $st = [];
                $st['goods_style_id'] = $goods_style_id;
                $st['style_name'] = $styleList[$goods_style_id] ?? '';
                $st['count'] = array_sum(array_column($item, 'count'));
                $st['total_piece_weight'] = bcdiv(array_sum(array_column($item, 'total_piece_weight')), 1000, 3);
                $st['total_netglod_weight'] = bcdiv(array_sum(array_column($item, 'total_netglod_weight')), 1000, 3);
                $st['label_price'] = bcdiv(array_sum(array_column($item, 'label_price')), 100, 2);
                $st['total_cost_fee'] = bcdiv(array_sum(array_column($item, 'total_cost_fee')), 100, 2);
                $styleData[] = $st;
            }

            $data['style_list'] = $styleData;

            $newData[] = $data;
        }
        return $newData;
    }


    /**
     * 明细列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getdetail(Request $request)
    {
        $list = $this->getDetialData($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }


    /**
     * 导出
     */
    public function detailexport(Request $request)
    {
        $type = $request->type ?? 0;
        $list = $this->getDetialData($request)['list'];
        $row = [
            ['table_header' => '入库汇总明细'],
            [
                'startstore' => '起始门店',
                'targetstore' => '目的门店',
                'stockin_at' => '入库日期',
                'supply_name' => '供应商',
                'style_name' => '款式',
                'goods_sn_code' => '条码',
                'goods_name' => '品名',
                'category_name' => '商品类别',
                'count' => '数量',
                'gramprice_fee' => '克销工费',
                'label_price' => '标签价',
                'pieceprice_fee' => '件销工费',
                'piece_weight' => '入库件重',
                'piece_weight_new' => '件重',
                'total_piece_weight' => '入库总件重',
                'total_piece_weight_new' => '总件重',
                'netglod_weight' => '入库金重',
                'netglod_weight_new' => '金重',
                'total_netglod_weight' => '入库总金重',
                'total_netglod_weight_new' => '总金重',
                'content' => '含量',
                'costglod_price' => '成本金价',
                'repllennish_costglod_price' => '补货金价',
                'costpiece_fee' => '件成本工费',
                'costgram_fee' => '克成本工费',
                'piececost_fee' => '单件成本',
                'total_cost_fee' => '总成本',
                'goods_craft_name' => '工艺',
                'c_no' => '圈号',
                's_no' => '款号',
                'gemstone_fee1' => '宝石费1',
                'gemstone_fee2' => '宝石费2',
                'add_fee1' => '附加费1',
                'add_fee2' => '附加费2',
                'brand_name' => '品牌',
                'cf_no' => '证书号', //Z
                'cf_no_gia' => 'GIA证书号',
                'cf_fee' => '证书费',
                'main_stone_weigth' => '主石重',
                'main_stone_count' => '主石数',
                'other_stone_weigth' => '副石重',
                'other_stone_count' => '副石数',
                'color' => '颜色',
                'clarity' => '净度',
                'main_stone_val' => '主石值',
                'other_stone_val' => '副石值',
                'cut' => '切工',
                'goods_pricetype_name' => '价格类型',
                'goods_stone_name' => '石料材质',
                'audit_at' => '库存时间',
                'paytype_name' => '支付方式',
                'paymoney' => '应付账款',
                'is_code_more' => '一码多货',
                'remark' => '备注',
                'audit_status' => '审核状态'
            ]];

        //成本金价、补货金价、件成本工费、克成本工费、单件成本、总成本、应付账款这些字段都去掉
        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[1]['costglod_price']);
            unset($row[1]['repllennish_costglod_price']);
            unset($row[1]['costpiece_fee']);
            unset($row[1]['costgram_fee']);
            unset($row[1]['piececost_fee']);
            unset($row[1]['total_cost_fee']);
            unset($row[1]['paymoney']);
        }

        $exceldata = [];
        foreach ($list as $val) {
            $goods_category = $val['goods_category'] ?? [];
            if (in_array($type, [1, 2])) {
                $startstore = '财务部';
                $targetstore = $val['storeinfo']['store_name'] ?? '';
            } else if (in_array($type, [3, 4])) {
                $startstore = $val['startstore']['store_name'] ?? '';
                $targetstore = $val['targetstore']['store_name'] ?? '';
            } else {
                $startstore = $val['storeinfo']['store_name'] ?? '';
                $targetstore = '财务部';
            }

            $exceldata[] = [
                'startstore' => $startstore,
                'targetstore' => $targetstore,
                'stockin_at' => date('Y-m-d', $val['stockin_at']),
                'supply_name' => isset($val['supply']['supply_name']) ? $val['supply']['supply_name'] : '',
                'style_name' => $val['goods_style']['style_name'],
                'goods_sn_code' => "{$val['goods_sn_code']} ",
                'goods_name' => $val['goods_name'],
                'category_name' => $goods_category['category_name'] ?? '',
                'count' => $val['count'],
                'gramprice_fee' => $val['gramprice_fee'] / 100,
                'label_price' => $val['label_price_new'] / 100,
                'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                'piece_weight' => $val['piece_weight'],
                'piece_weight_new' => $val['piece_weight_new'],
                'netglod_weight' => $val['netglod_weight_new'],
                'total_piece_weight' => $val['total_piece_weight'] ?? '',
                'total_piece_weight_new' => $val['total_piece_weight_new'] ?? '',
                'total_netglod_weight' => $val['total_netglod_weight'] ?? '',
                'total_netglod_weight_new' => $val['total_netglod_weight_new'] ?? '',
                'content' => isset($val['goods_content']['content_name']) ? $val['goods_content']['content_name'] : '',
                'costglod_price' => $val['costglod_price'] / 100,
                'repllennish_costglod_price' => empty($val['repllennish_costglod_price'] ?? '') ? '' : ($val['repllennish_costglod_price'] / 100),
                'costpiece_fee' => $val['costpiece_fee'] / 100,
                'costgram_fee' => $val['costgram_fee'] / 100,
                'piececost_fee' => $val['piececost_fee'] / 100,
                'goods_craft_name' => isset($val['goods_craft']['craft_name']) ? $val['goods_craft']['craft_name'] : '',
                'c_no' => $val['c_no'],
                's_no' => $val['s_no'],
                'gemstone_fee1' => $val['gemstone_fee1'] / 100,
                'gemstone_fee2' => $val['gemstone_fee2'] / 100,
                'add_fee1' => $val['add_fee1'] / 100,
                'add_fee2' => $val['add_fee2'] / 100,
                'brand_name' => isset($val['goods_brand']['brand_name']) ? $val['goods_brand']['brand_name'] : '',
                'cf_no' => $val['cf_no'],
                'cf_no_gia' => $val['cf_no_gia'],
                'cf_fee' => $val['cf_fee'] / 100,
                'main_stone_weigth' => $val['main_stone_weigth'],
                'main_stone_count' => $val['main_stone_count'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'other_stone_count' => $val['other_stone_count'],
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'main_stone_val' => $val['main_stone_val'],
                'other_stone_val' => $val['other_stone_val'],
                'cut' => $val['cut'],
                'goods_pricetype_name' => isset($val['goods_pricetype']['goods_pricetype_name']) ? $val['goods_pricetype']['goods_pricetype_name'] : '',
                'goods_stone_name' => isset($val['goods_stone']['goods_stone_name']) ? $val['goods_stone']['goods_stone_name'] : '',
                'audit_at' => ($val['procure_at'] ?? 0) > 0 ? (date('Y-m-d H:i:s', $val['audit_at'])) : ($val['audit_at'] > 0 ? date('Y-m-d H:i:s', $val['audit_at']) : ''),
                'paytype_name' => isset($val['paytype']['paytype_name']) ? $val['paytype']['paytype_name'] : '',
                'paymoney' => $val['paymoney'] / 100,
                'is_code_more' => $val['is_code_more'] == 1 ? '否' : '是',
                'remark' => $val['remark'] ?? '',
                'audit_status' => $val['audit_status'] == 1 ? '待审核' : ($val['audit_status'] == 2 ? '审核' : '取消'),
                'total_cost_fee' => ($val['total_cost_fee'] ?? 0) > 0 ? ($val['total_cost_fee'] / 100) : 0
            ];
        }

        $filename = '入库汇总明细导出_' . time() . '.xlsx';
        $datawith = [
            'A' => '30', 'B' => '10', 'C' => '30', 'D' => '30', 'E' => '30', 'F' => '30', 'G' => '30', 'H' => '30', 'J' => '30', 'K' => '30', 'L' => '30', 'M' => '30',
            'O' => '30', 'P' => '30', 'Q' => '30', 'R' => '30', 'S' => '30', 'T' => '30', 'U' => '30', 'V' => '30', 'W' => '30', 'X' => '30', 'Y' => '30', 'Z' => '30',
            'AA' => '30', 'AB' => '10', 'AC' => '30', 'AD' => '30', 'AE' => '30', 'AF' => '30', 'AG' => '30', 'AH' => '30', 'AJ' => '30', 'AK' => '30', 'AL' => '30', 'AM' => '30',
            'AO' => '30', 'AP' => '30', 'AQ' => '30', 'AR' => '30', 'AS' => '30', 'AT' => '30', 'AU' => '30', 'AV' => '30', 'AW' => '30', 'AX' => '30', 'AY' => '30', 'AZ' => '30',
            'BA' => '30', 'BB' => '10', 'BC' => '30',
        ];
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }

    /**
     * 获取明细 数据
     * @param Request $request
     * @return array|\Illuminate\Http\JsonResponse
     */
    public function getDetialData(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $where = [];
        $type = (int)$request['type'] ?? 0;
        $store_id = $request['store_id'] ?? 0;

        $where[] = ['cp_id', '=', $cp_id];
        $audit_status = $request['audit_status'] ?? 1;
        if ($audit_status > 1) {
            $where[] = ['audit_status', '=', $audit_status];
        } else {
            $where[] = ['audit_status', '<>', 1];
        }

        if (!empty($store_id)) {
            $where[] = ['store_id', '=', $store_id];
        }

        if (!empty($request['goods_style_id'])) {
            $where[] = ['goods_style_id', '=', $request['goods_style_id']];
        }

        if (!empty($request['goods_category_id'])) {
            $where[] = ['goods_category_id', '=', $request['goods_category_id']];
        }

        // 权限
        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        $store_ids = is_array($store_ids) ? $store_ids : ($store_ids > 0 ? [$store_ids] : []);

        $virtuallyCate = GoodsCategory::query()
            ->where(['cp_id' => $cp_id, 'is_del' => 1, 'is_virtually' => 1])
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                if (is_array($store_ids)) {
                    $query->whereIn('store_id', $store_ids);
                } else {
                    $query->where('store_id', $store_ids);
                }
            })
            ->get(['id'])
            ->pluck('id')
            ->toArray();


        $cateIds = [];
        // 查询柜组
        if (!empty($request['goods_cabinetgroup_id'])) {
            $cateIds = GoodsCategory::query()
                ->where(['goods_cabinetgroup_id' => $request['goods_cabinetgroup_id'], 'is_del' => 1, 'cp_id' => $cp_id])
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                })
                ->pluck('id')
                ->toArray();
        }
        // 时间段查询
        $start_time = $request['start_time'];
        $end_time = $request['end_time'];

        if (!empty($start_time) && !empty($end_time)) {

            $start_time = (!is_numeric($start_time) && strtotime($start_time) > 0) ? strtotime($start_time) : intval($start_time);
            $end_time = (!is_numeric($end_time) && strtotime($end_time) > 0) ? strtotime($end_time) : intval($end_time);
            $start_time = strtotime(date('Y-m-d', $start_time) . ' 00:00:00');
            $end_time = strtotime(date('Y-m-d', $end_time) . ' 23:59:59');

            $where[] = ['audit_at', '>=', $start_time];
            $where[] = ['audit_at', '<=', $end_time];
        }


        $limit = $request->limit ?? 10;
        $page = $request->page ?? 0;


        // 1入库，2补货，调拨(3调出、4调入)，5返厂
        if ($type == 1) {
            $query = GoodsStockinInfolist::query()
                ->with(['storeinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand', 'goods_content'])
                ->where($where)
                ->where('count', '>', 0)
                ->when(count($virtuallyCate) > 0, function ($query) use ($virtuallyCate) {
                    $query->whereNotIn('goods_category_id', $virtuallyCate);
                })
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($cateIds) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                });
            if ($page > 0) {
                $list = $query->paginate($limit)->toArray();
                $list = Common::paginateDataToArray($list);
            } else {
                $list['list'] = $query->get()->toArray();
            }

        } elseif ($type == 2) {
            // 补货
            $query = GoodsReplenishInfolist::query()
                ->with(['storeinfo', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info', 'goods_brand'])
                ->where($where)
                ->where('count_new', '>', 0)
                ->when(count($virtuallyCate) > 0, function ($query) use ($virtuallyCate) {
                    $query->whereNotIn('goods_category_id', $virtuallyCate);
                })
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereIn('goods_category_id', $cateIds);
                })
                ->when(count($store_ids) > 0, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                });
            if ($page > 0) {
                $list = $query->paginate($limit)->toArray();
                $list = Common::paginateDataToArray($list);
            } else {
                $list['list'] = $query->get()->toArray();
            }
            foreach ($list['list'] as &$item) {
                $item['count'] = $item['count_new'];
            }
        } elseif (in_array($type, [3, 4])) {
            foreach ($where as $key => $val) {
                if ($val[0] == 'store_id') {
                    unset($where[$key]);
                }
                if ($val[0] == 'goods_category_id') {
                    unset($where[$key]);
                }
            }

            //调拨(3调出、4调入)
            if ($type == 3) {

                if ($store_id > 0) {
                    $where[] = ['start_store_id', '=', $store_id];
                }
                if (!empty($request['goods_category_id'])) {
                    $where[] = ['goods_category_id', '=', $request['goods_category_id']];
                }

            } else {
                if ($store_id > 0) {
                    $where[] = ['target_store_id', '=', $store_id];

                }
                if (!empty($request['goods_category_id'])) {
                    $where[] = ['target_category_id', '=', $request['goods_category_id']];
                }
            }


            $where = array_values($where);

            $query = GoodsAllotInfolist::query()
                ->with(['startstoreinfo', 'targetstoreinfo', 'goods_brand', 'goods_category', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info'])
                ->where($where)
                ->where('count_new', '>', 0)
                ->when($type == 3, function ($query) use ($store_ids, $cateIds, $virtuallyCate) {

                    if (count($store_ids) > 0) {
                        $query->whereIn('start_store_id', $store_ids);
                    }
                    if (count($cateIds) > 0) {
                        $query->whereIn('goods_category_id', $cateIds);
                    }
                    if (count($virtuallyCate) > 0) {
                        $query->whereNotIn('goods_category_id', $virtuallyCate);
                    }
                })
                ->when($type == 4, function ($query) use ($store_ids, $cateIds, $virtuallyCate) {
                    if (count($store_ids) > 0) {
                        $query->whereIn('target_store_id', $store_ids);
                    }
                    if (count($cateIds) > 0) {
                        $query->whereIn('target_category_id', $cateIds);
                    }
                    if (count($virtuallyCate) > 0) {
                        $query->whereNotIn('target_category_id', $virtuallyCate);
                    }
                });

            if ($page > 0) {
                $list = $query->paginate($limit)->toArray();
                $list = Common::paginateDataToArray($list);
            } else {
                $list['list'] = $query->get()->toArray();
            }

            foreach ($list['list'] as &$item) {
                $item['count'] = $item['count_new'];
            }

        } elseif ($type == 5) {
            $query = GoodsReturnInfolist::query()
                ->with(['storeinfo', 'goods_brand', 'goods_category', 'supply', 'goods_style', 'goods_craft', 'goods_pricetype', 'goods_stone', 'paytype_info'])
                ->where($where)
                ->where('count_new', '>', 0)
                ->when(count($virtuallyCate) > 0, function ($query) use ($virtuallyCate) {
                    $query->whereNotIn('goods_category_id', $virtuallyCate);
                })
                ->when(count($cateIds) > 0, function ($query) use ($cateIds) {
                    $query->whereNotIn('goods_category_id', $cateIds);
                })
                ->when(count($store_ids) > 0 && (int)$type == 3, function ($query) use ($store_ids) {
                    $query->whereIn('store_id', $store_ids);
                });

            if ($page > 0) {
                $list = $query->paginate($limit)->toArray();
                $list = Common::paginateDataToArray($list);
            } else {
                $list['list'] = $query->get()->toArray();
            }

            foreach ($list['list'] as &$item) {
                $item['count'] = $item['count_new'];
            }
        } else {
            return response()->json(['code' => '001', 'msg' => '传入的类型错误']);
        }

        return $list;
    }
}
